package com.wimcorp.magic.client.input;

import java.util.concurrent.*;

public class ConsoleInput {
	private final CountDownLatch actuallyFinishedLatch = new CountDownLatch(1);
	private final Object lock = new Object();
	
	private Future<String> result;

	public String readLine() throws InterruptedException {
		ExecutorService ex = Executors.newSingleThreadExecutor();
		String input = null;
		try {
			while (input == null) {
				result = ex.submit(new ConsoleInputReadTask());
				try {
					input = result.get();
					break;
				} catch (CancellationException ce) {
					throw new CancellationException(ce.getMessage());
				} catch (ExecutionException e) {
					e.getCause().printStackTrace();
				}
			}
		} finally {
			ex.shutdownNow();
			actuallyFinishedLatch.countDown();
		}
		return input;
	}

	public void cancel() {
		while (result == null) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		result.cancel(true);
		try {
			actuallyFinishedLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public Object getLock() {
		return lock;
	}

	
	
}